const kitchenService = require('../../services/kitchenService');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    kitchenId: '',
    kitchen: {},
    dishes: [],
    loading: true,
    theme: '',  // 添加主题数据
    fromMealPlan: false,
    mealType: 'breakfast'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'theme-green';
    this.setData({ theme });
    
    if (options.id) {
      this.setData({
        kitchenId: options.id,
        loading: true
      });
      
      // 检查是否从饮食计划页面跳转过来
      if (options.from === 'mealplan') {
        this.setData({
          fromMealPlan: true,
          mealType: options.mealType || 'breakfast'
        });
      }
      
      this.loadKitchenDetail(options.id);
    }
  },

  /**
   * 加载厨房详情数据
   */
  async loadKitchenDetail(id) {
    this.setData({ loading: true });
    
    try {
      // 获取厨房详情
      const kitchen = await kitchenService.getKitchenById(id);
      
      if (!kitchen) {
        wx.showToast({
          title: '找不到厨房信息',
          icon: 'none'
        });
        this.setData({ loading: false });
        return;
      }
      
      // 获取厨房下的菜品
      const dishes = await kitchenService.getDishesForKitchen(id);
      
      this.setData({
        kitchen: kitchen,
        dishes: dishes,
        loading: false
      });
    } catch (error) {
      console.error('加载厨房详情失败', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  },

  /**
   * 设置为默认厨房
   */
  async setAsDefault() {
    wx.showLoading({
      title: '设置中...',
      mask: true
    });
    
    try {
      const success = await kitchenService.setDefaultKitchen(this.data.kitchenId);
      wx.hideLoading();
      
      if (success) {
        // 显示成功提示
        wx.showToast({
          title: '已设为默认',
          icon: 'success',
          duration: 1500
        });
        
        // 重新加载厨房数据以更新当前界面显示
        this.loadKitchenDetail(this.data.kitchenId);
        
        // 设置一个延迟，让用户看到成功提示
        setTimeout(() => {
          // 直接跳转到厨房主页，并强制刷新
          wx.reLaunch({
            url: '/pages/kitchen/kitchen',
            success: () => {
              console.log('成功跳转到厨房主页，显示新的默认厨房');
            },
            fail: (err) => {
              console.error('跳转到厨房主页失败', err);
            }
          });
        }, 1500);
      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('设置默认厨房失败', error);
      wx.showToast({
        title: '设置失败',
        icon: 'none'
      });
    }
  },

  /**
   * 编辑厨房信息
   */
  editKitchen() {
    wx.navigateTo({
      url: `/pages/kitchen-edit/kitchen-edit?id=${this.data.kitchenId}&mode=edit`
    });
  },

  /**
   * 分享厨房
   */
  shareKitchen() {
    wx.showActionSheet({
      itemList: ['分享给朋友', '生成分享图片', '复制链接'],
      success: (res) => {
        if (!res.cancel) {
          wx.showToast({
            title: '分享功能开发中',
            icon: 'none'
          });
        }
      }
    });
  },

  /**
   * 添加菜品
   */
  addDish() {
    wx.navigateTo({
      url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchenId}&mode=create`
    });
  },

  /**
   * 编辑菜品
   */
  editDish(e) {
    const dishId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchenId}&dishId=${dishId}&mode=edit`
    });
  },

  /**
   * 删除菜品
   */
  async removeDish(e) {
    const dishId = e.currentTarget.dataset.id;
    const dish = this.data.dishes.find(d => d._id === dishId);
    
    if (!dish) return;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${dish.name}"吗？此操作不可恢复。`,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
            mask: true
          });
          
          try {
            const success = await kitchenService.deleteDish(this.data.kitchenId, dishId);
            wx.hideLoading();
            
            if (success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              // 重新加载厨房数据
              this.loadKitchenDetail(this.data.kitchenId);
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            wx.hideLoading();
            console.error('删除菜品失败', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 刷新数据，以防在其他页面进行了修改
     // 检查主题是否有变化
     const theme = wx.getStorageSync('theme');
     if (theme !== this.data.theme) {
       this.setData({ theme });
     }
    if (this.data.kitchenId) {
      this.loadKitchenDetail(this.data.kitchenId);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `${this.data.kitchen.name} - 我的厨房`,
      path: `/pages/kitchen-detail/kitchen-detail?id=${this.data.kitchenId}`
    };
  },

  /**
   * 查看或选择菜品
   */
  navigateToDish(e) {
    const dishId = e.currentTarget.dataset.id;
    const dish = this.data.dishes.find(d => d._id === dishId);
    
    if (!dish) return;
    
    // 如果是从饮食计划页面跳转过来的，则是选择菜品
    if (this.data.fromMealPlan) {
      this.selectDishForMealPlan(dish);
    } else {
      // 否则是查看菜品详情
      wx.navigateTo({
        url: `/pages/dish-detail/dish-detail?kitchenId=${this.data.kitchenId}&dishId=${dishId}`
      });
    }
  },
  
  /**
   * 选择菜品到饮食计划
   */
  selectDishForMealPlan(dish) {
    wx.showModal({
      title: '添加到饮食计划',
      content: `确定将"${dish.name}"添加到${this.getMealTypeText(this.data.mealType)}吗？`,
      success: (res) => {
        if (res.confirm) {
          // 获取页面实例
          const eventChannel = this.getOpenerEventChannel();
          
          // 增加日志，检查事件通道是否存在
          console.log('事件通道:', eventChannel);
          
          // 通过事件通道发送选中的菜品数据
          if (eventChannel && eventChannel.emit) {
            // 添加营养信息，确保饮食计划页能计算正确的营养摄入
            const dishWithNutrition = {
              ...dish,
              nutrition: dish.nutrition || {
                protein: 0,
                carbs: 0,
                fat: 0
              },
              calories: dish.calories || 0
            };
            
            // 发送选中的菜品数据
            eventChannel.emit('selectDish', dishWithNutrition);
            console.log('成功发送选中菜品数据:', dishWithNutrition);
            
            // 返回上一页
            wx.navigateBack({
              delta: 2
            });
          } else {
            console.error('无法获取事件通道');
            wx.showToast({
              title: '添加失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },
  
  /**
   * 获取餐食类型的显示文本
   */
  getMealTypeText(type) {
    switch (type) {
      case 'breakfast': return '早餐';
      case 'lunch': return '午餐';
      case 'dinner': return '晚餐';
      default: return '未知';
    }
  }
}) 